//
//  YZMAccountDetailViewController.m
//  YZMicroStock
//
//  Created by Lv.Dongdong on 16/4/12.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMAccountDetailViewController.h"
#import "YZMAlertView.h"
#import "YZMSeparatorCell.h"
#import "YZMLockPassword.h"
#import "YZClient+Account.h"
#import "YZGeneralResultModel.h"
#import "YZClient+BankCard.h"
#import "YZMAppHelper.h"
#import <GeTuiSdk.h>

#define ACCOUNT_DETAIL_TAG_FOR_AVATAT  1000
#define ACCOUNT_DETAIL_TAG_FOR_IDENTITY_VERIFY       ACCOUNT_DETAIL_TAG_FOR_AVATAT + 1
#define ACCOUNT_DETAIL_TAG_FOR_PHONE                 ACCOUNT_DETAIL_TAG_FOR_IDENTITY_VERIFY + 1
#define ACCOUNT_DETAIL_TAG_FOR_LOGIN_PASSWORD        ACCOUNT_DETAIL_TAG_FOR_PHONE + 1
#define ACCOUNT_DETAIL_TAG_FOR_DRAW_PASSWORD         ACCOUNT_DETAIL_TAG_FOR_LOGIN_PASSWORD + 1
#define ACCOUNT_DETAIL_TAG_FOR_GESTURE_PASSWORD      ACCOUNT_DETAIL_TAG_FOR_DRAW_PASSWORD + 1
#define ACCOUNT_DETAIL_TAG_FOR_BANK_CARD             ACCOUNT_DETAIL_TAG_FOR_GESTURE_PASSWORD + 1
#define ACCOUNT_DETAIL_TAG_FOR_payZF                ACCOUNT_DETAIL_TAG_FOR_BANK_CARD + 1
#define ACCOUNT_DETAIL_TAG_FOR_NOTICE                ACCOUNT_DETAIL_TAG_FOR_payZF + 1
#define ACCOUNT_DETAIL_TAG_FOR_build                 ACCOUNT_DETAIL_TAG_FOR_NOTICE + 1

static NSString *const sYZMAccountDetailCellID = @"YZMAccountDetailCellID";

@interface YZMAccountDetailViewController () <UITableViewDelegate, UITableViewDataSource, GeTuiSdkDelegate>

@property (nonatomic, strong) NSArray *dataSource;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) YZMUser *user;

@end

@implementation YZMAccountDetailViewController

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (id)init{
    
    if (self = [super init]) {
        
        self.title = @"我的信息";
        self.hidesBottomBarWhenPushed = YES;
    }
    
    return self;
}

- (YZMUser *)user {
    
    if (!_user) {
        
        _user = YZMUserServiceInstance.user;
    }
    
    return _user;
}

- (NSArray *)dataSource {
    if (!_dataSource) {
        _dataSource = @[@[@[@"用户名", @(ACCOUNT_DETAIL_TAG_FOR_AVATAT)]],
                        
                        @[@[@"实名认证", @(ACCOUNT_DETAIL_TAG_FOR_IDENTITY_VERIFY)],
                          @[@"手机号码", @(ACCOUNT_DETAIL_TAG_FOR_PHONE)],
                          @[@"支付宝认证", @(ACCOUNT_DETAIL_TAG_FOR_payZF)]],
                        
                        @[@[@"登录密码", @(ACCOUNT_DETAIL_TAG_FOR_LOGIN_PASSWORD)],
                          @[@"提现密码", @(ACCOUNT_DETAIL_TAG_FOR_DRAW_PASSWORD)],
                          @[@"手势密码", @(ACCOUNT_DETAIL_TAG_FOR_GESTURE_PASSWORD)]],
                        
                        @[@[@"我的银行卡", @(ACCOUNT_DETAIL_TAG_FOR_BANK_CARD)]],
#ifdef YZMicroStock
                        @[@[@"消息提醒设置", @(ACCOUNT_DETAIL_TAG_FOR_NOTICE)]],
#endif
                        @[@[@"版本信息", @(ACCOUNT_DETAIL_TAG_FOR_build)]],
                        ];
    }
    return _dataSource;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.view.backgroundColor = [YZMAppStyle appBackgroundColor];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(RefeshPushSwitch) name:@"refeshPushSwitch" object:nil];
    [self createObjects];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:YES];
    [self fetchUserDetail:nil];
}

- (void)RefeshPushSwitch {
    
    [self.tableView reloadData];
}

- (void)fetchUserDetail:(NSNotification *)noti {
    
    [YZMUserServiceInstance fetchUserDetailSuccess:^{
        
        self.user.detail = YZMUserServiceInstance.user.detail;
        [self.tableView reloadData];
        
    } failure:nil];
    
    [YZMUserServiceInstance fetchUserBankCardSuccess:^{
        
        [self.tableView reloadData];
        
    } failure:nil];
}

#pragma mark -- Private Method

- (void)createObjects{
    
    WS(ws)
    self.tableView = [[UITableView alloc] init];
    self.tableView.backgroundColor = [YZMAppStyle appBackgroundColor];
    self.tableView.backgroundView = nil;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make){
        
        make.edges.equalTo(ws.view);
    }];
    
    
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 100)];
    footerView.backgroundColor = [UIColor clearColor];
    self.tableView.tableFooterView = footerView;
    
    UIButton *exitButton = [YZMAppStyle submitButton];
    exitButton.enabled = YES;
    [exitButton setTitle:@"退出登录" forState:UIControlStateNormal];
    [exitButton addTarget: self action: @selector(exitButtonPressed:) forControlEvents: UIControlEventTouchUpInside];
    [footerView addSubview:exitButton];
    [exitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(footerView.mas_top).with.offset(5);
        make.left.equalTo(ws.view).with.offset(ControlSpacing15);
        make.right.equalTo(ws.view).with.offset(-ControlSpacing15);
    }];
    
}

- (void)exitButtonPressed: (id)sender
{
    YZMAlertView *alertView = [[YZMAlertView alloc] init];
    alertView.titleLabel.text = @"退出登录";
    alertView.contentLabel.text = @"确定退出当前账号?";
    alertView.contentLabel.textAlignment = NSTextAlignmentCenter;
    alertView.confirmHandle = ^()
    {
        [YZMUserServiceInstance logoutSuccess:^{
            [YZMHCMInstance popToRootViewController];
        } failure:^(NSError *error) {
            [error yz_showMessage];
        }];
        return YES;
    };
    [alertView show];
}

- (void)switchValueChanged:(UISwitch *)sender {
    
    BOOL isOff = [[NSUserDefaults standardUserDefaults] boolForKey:@"isGeTuiModel"];
    NSLog(@"%@", @(isOff));
    [GeTuiSdk setPushModeForOff:isOff];
}

#pragma mark -- TableView DataSource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    YZMSeparatorCell *cell = [tableView dequeueReusableCellWithIdentifier:sYZMAccountDetailCellID];
    
    if (!cell) {
        cell = [[YZMSeparatorCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:sYZMAccountDetailCellID];
    }
    
    cell.textLabel.text = nil;
    cell.detailTextLabel.text = nil;
    cell.accessoryView = nil;
    cell.imageView.image = nil;
    cell.detailTextLabel.textColor = [YZMAppStyle colorForGrayText];
    cell.detailTextLabel.font = [YZMAppStyle mediumSizeFont];
    
    YZMIndexCount indexCount;
    
    indexCount.index = indexPath.row;
    indexCount.count = [self.dataSource[indexPath.section] count];
    cell.indexCount = indexCount;
    
    NSArray *tempArray = self.dataSource[indexPath.section][indexPath.row];
    NSInteger tag = [tempArray[1] integerValue];
    cell.textLabel.textColor = [YZMAppStyle colorForMainTextColor];
    cell.textLabel.font = [YZMAppStyle mediumSizeFont];
    cell.detailTextLabel.textColor = [YZMAppStyle colorForGrayText];
    cell.detailTextLabel.font = [YZMAppStyle mediumSizeFont];
    
    switch (tag) {
        case ACCOUNT_DETAIL_TAG_FOR_AVATAT: {
            
            UIView *lineView = [YZMAppStyle splitLine];
            [cell.contentView addSubview:lineView];
            [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
                
                make.top.left.right.equalTo(cell.contentView);
            }];
            
            cell.imageView.image = [UIImage imageNamed:@"avatar"];
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.selectionStyle = NO;
            
            if (YZMUserServiceInstance.currentUser.username) {
                
                cell.textLabel.text = YZMUserServiceInstance.currentUser.username;
                cell.textLabel.font = [YZMAppStyle fontWithSize:17];
            }
        }
            break;
        case ACCOUNT_DETAIL_TAG_FOR_IDENTITY_VERIFY: {
            
            cell.textLabel.text = tempArray[0];
            
            if (YZMUserServiceInstance.user.detail.isNamed) {
                
                if(YZMUserServiceInstance.user.detail.nameVerifyStatus.length == 0){
                    cell.detailTextLabel.text = @"已认证";
                }else{
                    cell.detailTextLabel.text = YZMUserServiceInstance.user.detail.nameVerifyStatus;
                }
                cell.detailTextLabel.textColor = [YZMAppStyle colorForMainTextColor];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.accessoryType = UITableViewCellAccessoryNone;
            } else {
                
                if (YZMUserServiceInstance.user.detail.identityVerify != 0) {
                    cell.detailTextLabel.text = YZMUserServiceInstance.user.detail.nameVerifyStatus;
                    cell.detailTextLabel.textColor = [YZMAppStyle colorForRiseText];
                    cell.detailTextLabel.minimumScaleFactor = 0.5;
                    cell.detailTextLabel.adjustsFontSizeToFitWidth = YES;
                    cell.selectionStyle = UITableViewCellSelectionStyleNone;
                    cell.accessoryType = UITableViewCellAccessoryNone;
                }else{
                    cell.detailTextLabel.text = @"未认证";
                    cell.selectionStyle = UITableViewCellSelectionStyleDefault;
                    cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"left_arrow"]];
                }
            }
            
        }
            break;
        case ACCOUNT_DETAIL_TAG_FOR_PHONE: {
            
            cell.textLabel.text = tempArray[0];
            cell.detailTextLabel.text = YZMUserServiceInstance.user.detail.loginMobile;
            cell.detailTextLabel.textColor = [YZMAppStyle colorForMainTextColor];
            cell.selectionStyle = NO;
//            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"left_arrow"]];

        }
            break;
        case ACCOUNT_DETAIL_TAG_FOR_LOGIN_PASSWORD: {
            
            cell.textLabel.text = tempArray[0];
            cell.detailTextLabel.text = @"修改";
            cell.detailTextLabel.textColor = [YZMAppStyle colorForGrayText];
            cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"left_arrow"]];
        }
            break;
        case ACCOUNT_DETAIL_TAG_FOR_DRAW_PASSWORD: {
            
            cell.textLabel.text = tempArray[0];
            cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"left_arrow"]];
            cell.detailTextLabel.textColor = [YZMAppStyle colorForGrayText];
            if (self.user.detail.isWithDrawPw) {
                
                cell.detailTextLabel.text = @"修改";
            } else {
                
                cell.detailTextLabel.text = @"未设置";
            }
            
        }
            break;
        case ACCOUNT_DETAIL_TAG_FOR_GESTURE_PASSWORD: {
            
            cell.textLabel.text = tempArray[0];
            cell.detailTextLabel.textColor = [YZMAppStyle colorForGrayText];
            
            if ([YZMLockPassword loadLockPassword]) {
                
                cell.detailTextLabel.text = @"已开启";
            }else{
                
                cell.detailTextLabel.text = @"未开启";
            }
            
            cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"left_arrow"]];
        }
            break;
        case ACCOUNT_DETAIL_TAG_FOR_BANK_CARD: {
            
            cell.textLabel.text = tempArray[0];
            if (YZMUserServiceInstance.user.bankCardList.count != 0) {
                
                cell.detailTextLabel.text = [NSString stringWithFormat:@"%@张",@(YZMUserServiceInstance.user.bankCardList.count)];
                cell.detailTextLabel.textColor = [YZMAppStyle colorForGrayText];
            }else{
                
                cell.detailTextLabel.text = @"未绑定";
                cell.detailTextLabel.textColor = [YZMAppStyle colorForGrayText];
            }
            indexCount.index = indexPath.row;
            indexCount.count = [self.dataSource[indexPath.section] count];
            cell.indexCount = indexCount;
            cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"left_arrow"]];
        }
            break;
        case ACCOUNT_DETAIL_TAG_FOR_payZF: {
            
            cell.textLabel.text = tempArray[0];
            cell.detailTextLabel.textColor = [YZMAppStyle colorForGrayText];
            
            if (YZMUserServiceInstance.user.detail.bindingpayZFAccount) {
                
                cell.detailTextLabel.text = @"已认证";
                cell.detailTextLabel.textColor = [YZMAppStyle colorForBlueText];

            }else{
                
                cell.detailTextLabel.text = @"未认证";
            }
            
            cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"left_arrow"]];
        }
            break;
            
        case ACCOUNT_DETAIL_TAG_FOR_NOTICE:{
        
            cell.textLabel.text = tempArray[0];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            UISwitch *switchview = [[UISwitch alloc] initWithFrame:CGRectZero];
            switchview.onTintColor = [YZMAppStyle colorForIconColor];
            //isGeTuiModel YES:开启 NO:关闭
            BOOL isOn = [[NSUserDefaults standardUserDefaults] boolForKey:@"isGeTuiModel"];
            switchview.on = isOn;
            [switchview addTarget: self action:@selector(switchValueChanged:) forControlEvents:UIControlEventValueChanged];
            cell.accessoryView = switchview;
        }
            break;
        case ACCOUNT_DETAIL_TAG_FOR_build:{
            cell.textLabel.text = tempArray[0];
            cell.detailTextLabel.textColor = [YZMAppStyle colorForWhite];
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%@.%@",[YZMAppHelper version],[YZMAppHelper buildVersion]];
        }
            break;
        default:
            break;
    }
    
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [self.dataSource[section] count];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.dataSource.count;
}
    
#pragma mark TableView Delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSArray *tempArray = self.dataSource[indexPath.section][indexPath.row];
    NSInteger tag = [tempArray[1] integerValue];
    switch (tag) {
        case ACCOUNT_DETAIL_TAG_FOR_AVATAT:
            
            break;
            
        case ACCOUNT_DETAIL_TAG_FOR_IDENTITY_VERIFY: {
            
            if (!YZMUserServiceInstance.user.detail.isNamed && YZMUserServiceInstance.user.detail.identityVerify == 0) {
                [YZMHCMInstance pushViewControllerWithName:@"identifyVerify" andParams:nil];
            }
        }
            break;
        case ACCOUNT_DETAIL_TAG_FOR_PHONE:
            
            [YZMHCMInstance pushViewControllerWithName:@"phoneconfirm" andParams:@{YZSOURCEPAGE:@"accountDetail"}];
            
            break;
        case ACCOUNT_DETAIL_TAG_FOR_LOGIN_PASSWORD: {
            
            [YZMHCMInstance pushViewControllerWithName:@"changeLoginPwd" andParams:nil];
        }
            break;
        case ACCOUNT_DETAIL_TAG_FOR_DRAW_PASSWORD: {
            
            if (self.user.detail.isWithDrawPw) {
                
                [YZMHCMInstance pushViewControllerWithName:@"changeWdPwd" andParams:nil];
            } else {
                
                [YZMHCMInstance pushViewControllerWithName:@"setWdPwd" andParams:nil];
            }
            
        }
            break;
        case ACCOUNT_DETAIL_TAG_FOR_GESTURE_PASSWORD: {
            
            
            
            [YZMHCMInstance pushViewControllerWithName:@"gesture" andParams:nil];
            
        }
            break;
        case ACCOUNT_DETAIL_TAG_FOR_BANK_CARD: {
            
            [YZMHCMInstance pushViewControllerWithName:@"bankCardList" andParams:nil];
        }
            break;
        case ACCOUNT_DETAIL_TAG_FOR_payZF: {
        
            if (YZMUserServiceInstance.user.detail.bindingpayZFAccount) {
                
                [YZMAppHelper changepayZFAccount];
            }else{
                
                YZMAlertView *alertView = [YZMAlertView alertViewForRecommandWithContent:@"使用支付宝进行首次入金操作后，即可自动绑定支付宝账号。"];
                alertView.contentLabel.font = [YZMAppStyle mediumSizeFont];
                [alertView.sureButton setTitle:@"去充值" forState:UIControlStateNormal];
                alertView.cancelButton.hidden = NO;
                alertView.confirmHandle = ^(){
                    
                    [YZMHCMInstance pushViewControllerWithName:@"payform" andParams:nil];
                    return YES;
                };
                [alertView show];
                
//                [YZMHCMInstance pushViewControllerWithName:@"payZFAuth" andParams:nil];
            }
        }
            break;
        default:
            break;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.section) {
        case 0:
            return 100;
        default:
            return 60;
    }

}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{

    return ControlSpacing15;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    return [UIView new];
}

@end
